import { useState, Suspense, useMemo, useEffect } from 'react'
import { Image, List, Stepper, Button, Checkbox, Divider, Radio, Toast, Dialog } from 'antd-mobile'
import { DeleteOutline } from 'antd-mobile-icons'
import { useRoutes, useLocation, useNavigate, NavLink } from 'react-router-dom'
import { getCar, delGoods, onPay } from '../../api/car'
import './style.scss'
import { userInfo } from '../../api/user'
import { getGoods } from '../../api/goods'
import user from '../../store/user'

const Cart = () => {
  console.log(user.profile.id, 'user.profile.id')
  const [cartList, setCartlist] = useState<any>([])
  //获取购物车数据
  const getCarlist = async () => {
    let res = await getCar(user.profile.id as string)
    console.log(res, '购物车数据')
    setCartlist(res.data.cart)
  }

  //删除购物车
  const del_goods = async (id: any) => {
    const result = await Dialog.confirm({
      content: "确定删除",
    });
    if (result) {
      let res = await delGoods(user.profile.id, id);
      getCarlist()
      console.log(res, "shanchu");
      if (res.data.code == 200) {
        Toast.show({
          content: "删除成功",
          position: "bottom",
          afterClose: () => {
            getCarlist();
          },
        });
      }
    } else {
      Toast.show({ content: "取消删除", position: "bottom" });
    }
  }
  const add = (obj: any, value: any) => {
    // item.addtotal = value
    setCartlist(cartList.map((item: any) => {
      if (item.goods_id == obj.goods_id) {
        item.is_select = value
      }
      return item
    }))
  }
  //计算总价
  const totalPrice = useMemo(
    () =>
      cartList?.length &&
      //筛选是true的
      cartList.filter((item: any) => item.is_select).reduce((total: any, next: any) => {
        return total + next.cart_number * parseFloat(next.current_price)
      }, 0),
    [cartList]
  );
  // const totalPrice = 0
  //  去支付
  const goPay = async () => {
    let res = await onPay({ id: user.profile.id })
    console.log(res, '支付')
  }
  useEffect(() => {
    // localStorage.setItem(
    //   "token",
    //   'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MjQsI…DcyfQ.J7AvBeuTYxtPU93JJQ1xjt4YO-U7ivFePIbi2r7pnyc'
    // );
    getCarlist()
  }, [])
  return (
    <div>
      {user.profile.token ? (cartList.length > 0 ? (<div>
        <List header={<div>购物车({cartList.length})</div>}>
          {
            cartList.map((item: any, i: number) => (
              <List.Item
                key={i}
                prefix={
                  <div style={{ display: 'flex', width: 70, justifyContent: 'space-between' }}>
                    <Checkbox onChange={(value) => add(item, value)} />
                    <Image
                      src={item.img_small_logo}
                      style={{ borderRadius: 20 }}
                      fit='cover'
                      width={40}
                      height={40}
                    />
                  </div>
                }
                extra={
                  <div className='cart_right'>
                    <Stepper
                      defaultValue={item.cart_number}
                      onChange={value => {
                        console.log(value)
                        setCartlist(cartList.map((ite: any) => {
                          if (ite.goods_id == item.goods_id) {
                            item.cart_number = value
                          }
                          return ite
                        }))
                        console.log(item, 'ite')
                      }}
                    />
                    <DeleteOutline style={{ marginLeft: 5 }} onClick={() => del_goods(item.goods_id)} color='var(--adm-color-danger)' />
                  </div>
                }
                description={item.current_price + '￥'}
              >
                <div className='goodtitle'>{item.title}</div>
              </List.Item>
            ))
          }
        </List>
        <List>
          <List.Item key='a1'
            style={{ width: '100%', position: 'fixed', left: 0, bottom: 50, }}
            extra={<Button onClick={goPay} style={{ width: 150, margin: 10, borderRadius: 30, background: 'linear-gradient(to right,red, orangeRed)', color: '#fff' }}>去支付</Button>}>
            <div style={{ fontSize: 16, margin: 10, color: '#000' }}>总计：<span style={{ color: 'orangeRed' }}>￥<span style={{ fontSize: 25 }}>{totalPrice}</span></span></div>
          </List.Item>
        </List>
      </div>) : (<div>请添加购物车</div>)) : <div>抱歉，您还没有登陆，<NavLink to='/login'>点击去登陆</NavLink></div>}

    </div>
  )
}

export default Cart